package health_system.health_system.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Controller to provide debugging information for WebSocket connections
 */
@Slf4j
@RestController
@RequestMapping("/ws-debug")
public class WebSocketHandshakeController {

    @Value("${server.servlet.context-path:/api}")
    private String contextPath;
    
    /**
     * Provides diagnostic information for WebSocket configuration
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getWebSocketInfo(HttpServletRequest request) {
        Map<String, Object> info = new HashMap<>();
        
        // Server info
        info.put("contextPath", contextPath);
        info.put("requestContextPath", request.getContextPath());
        info.put("serverName", request.getServerName());
        info.put("serverPort", request.getServerPort());
        info.put("scheme", request.getScheme());
        
        // WebSocket endpoints
        Map<String, String> endpoints = new HashMap<>();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        
        endpoints.put("momentWebSocket", "ws://" + request.getServerName() + ":" + request.getServerPort() + contextPath + "/moment/ws");
        endpoints.put("testWebSocket", "ws://" + request.getServerName() + ":" + request.getServerPort() + contextPath + "/test/ws");
        endpoints.put("stompWebSocket", "ws://" + request.getServerName() + ":" + request.getServerPort() + contextPath + "/ws");
        
        info.put("endpoints", endpoints);
        
        // Request headers
        Map<String, String> headers = new HashMap<>();
        request.getHeaderNames().asIterator().forEachRemaining(name -> 
            headers.put(name, request.getHeader(name))
        );
        info.put("requestHeaders", headers);
        
        log.info("WebSocket diagnostic information requested from: {}", request.getRemoteAddr());
        
        return new ResponseEntity<>(info, HttpStatus.OK);
    }
} 